package com.speedtickets.rest.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

import com.speedtickets.rest.models.Ticket;

public class TicketDAO {
	
	private static final String PERSISTENCE_UNIT_NAME = "com.speedtickets.rest";
    private static EntityManagerFactory emFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
    protected EntityManager em = emFactory.createEntityManager();;

    private static TicketDAO _instance;
     
    public EntityManager getEm() {
    	return em;
    }

    public void setEm( EntityManager em ) {
        this.em = em;
    }
    
    public static TicketDAO getInstance() {
         if(_instance == null){
            return new TicketDAO();
        } 
       return _instance; 
    }

    
    public void save( Ticket ticket ){
        em.getTransaction().begin(); 
        em.persist(ticket);
        em.getTransaction().commit();
    }
    
    public void update( Ticket ticket ){
    	em.getTransaction().begin(); 
        em.merge(ticket);
        em.getTransaction().commit();
    }
    
    public void delete( Ticket ticket ){
    	em.getTransaction().begin(); 
        em.remove(ticket);
        em.getTransaction().commit();
    }
    
    @SuppressWarnings("unchecked")
	public List<Ticket> findAll() {
    	Query query = em.createQuery( "Select t from Ticket t" );
    	List<Ticket> list = query.getResultList();
    	return list;
    }
    
    @SuppressWarnings("unchecked")
    public List<Ticket> findAll(Integer limit, Integer offset){
    	Query query = em.createQuery( "Select t from Ticket t" ).setFirstResult(offset).setMaxResults(limit);
		List<Ticket> list = query.getResultList();
    	return list;
    }
    
    public Ticket findById( Number id ){
    	return em.find( Ticket.class, id );
    }


}
